import React, { useEffect, useState, useRef } from 'react'
import { PageContainer } from '@ant-design/pro-components'
import { useModel, history, useSearchParams } from '@umijs/max'
import {
  Form,
  Select,
  Space,
  Button,
  Card,
  Divider,
  Input,
  Radio,
  InputNumber,
  Modal,
  Cascader,
  App,
  Checkbox,
  Spin,
  Result
} from 'antd'
import RichText from '@/components/RichText/RichText.jsx'
import TagInput from '@/components/TagInput'
import RentPlanCard from '@/components/RentPlanCard'
import SellPlanCard from '@/components/SellPlanCard'
import SpuCard from '@/components/SpuCard'
import SkuCard from '@/components/SkuCard'
import Upload from '@/components/Upload'
import GaintSet from '@/components/GaintSet/GaintSet.jsx'
import SelfPickup from '@/components/SelfPickup/SelfPickup.jsx'
import CITY from '@/utils/city.json'
import styles from './index.less'
import { getUnique } from '@/utils/utils'

const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 20 }
}
const addressLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 }
}
let timer = null
const originInitial = {
  quantity_type: 1,
  lease_start_date_set: 3,
  buy_recvconfirm_days: 3,
  fineness_id: 1,
  shipping_method: 1,
  return_method: 1
}

export default () => {
  const [searchParams] = useSearchParams()
  const [form] = Form.useForm()
  const [addressForm] = Form.useForm()
  const goodsType = Form.useWatch('quantity_type', form)
  const pageType = Number(searchParams.get('type')) || 1
  const disabled = pageType === 3
  const id = searchParams.get('id')
  const merchant_id = searchParams.get('merchant_id')

  const { message, modal } = App.useApp()

  const {
    SetFormRef,
    GetGoodFineness,
    GetRentPlan,
    GetGainSet,
    GetAddressList,
    SaveReturnAddress,
    GetGoodsClass,
    SaveGood,
    GetGoodsDetail,
    SetDisable,
    SaveAndActiveGoods,
    GetTerms,
    Sell,
    Rent
  } = useModel('Goods')
  const { GetOwnTakeCount, GetActiveOwnTakeList } = useModel('Deliver')
  const { platformType, contentWidth } = useModel('Global')
  const [goodsFineness, setGoodsFineness] = useState([])
  const [FormList, setFormList] = useState([])
  const [needFineness, setNeedFineness] = useState(false)
  const [addressModalFlag, setAddressModalFlag] = useState(false)
  const [addressModalLoading, setAddressModalLoading] = useState(false)
  const [initialValues, setInitialValues] = useState(originInitial)
  const [originPackagePlan, setOriginPackagePlan] = useState([])
  const [rentPlan, setRentPlan] = useState([])
  const [sellPlan, setSellPlan] = useState([])
  const [gainSet, setGainSet] = useState([])
  const [gainTab, setGainTab] = useState('rent')
  const [addressList, setAddressList] = useState([])
  const [goodsClassList, setGoodsClassList] = useState([])
  const [goodsInfo, setGoodsInfo] = useState(null)
  const [sellTermList, setSellTermList] = useState([])
  const [selfPickupList, setSelfPickupList] = useState([])
  const [pageLoading, setPageLoading] = useState(false)
  const [pickupListLoading, setPickupListLoading] = useState(false)
  const saveType = useRef(0)

  SetFormRef(form)

  const defaultFormList = [
    {
      title: '基础信息',
      type: 'wrapper',
      children: [
        {
          title: '商品标题',
          type: 'input',
          formProp: {
            name: 'goods_name',
            label: '商品标题',
            rules: [{ required: true, message: '请输入商品标题！' }]
          },
          itemProp: {
            placeholder: '请输入'
          }
        },
        {
          title: '副标题',
          type: 'input',
          formProp: {
            name: 'subtitle',
            label: '副标题',
            help: '营销副标题展示在主标题下方，最多不能超过20个字'
          },
          itemProp: {
            maxLength: 20,
            placeholder: '请输入'
          }
        },
        {
          title: '商品类型',
          type: 'radio',
          formProp: {
            name: 'quantity_type', //todo
            label: '商品类型',
            rules: [{ required: true }]
          },
          itemProp: {
            prop: {},
            list: [
              {
                label: '全新',
                value: 1
              },
              {
                label: '二手',
                value: 2
              }
            ]
          }
        },
        {
          title: '成色',
          type: 'radio',
          visibelCheck: true,
          checkName: 'fineness',
          formProp: {
            name: 'fineness_id',
            label: '成色',
            rules: [{ required: true }]
          },
          itemProp: {
            prop: {},
            list: goodsFineness
          }
        },
        {
          title: '营销标签',
          type: 'tag',
          formProp: {
            name: 'market_label',
            label: '营销标签',
            help: '营销标签最多可创建3个'
          }
        },
        {
          title: '行业类目',
          type: 'cascader',
          formProp: {
            name: 'goods_class_id',
            label: '行业类目',
            rules: [{ required: true }],
            help: '因支付宝平台相关规定，请准确选择经营许可范围内对应的商品类目'
          },
          itemProp: {
            options: goodsClassList,
            placeholder: '请选择商品类目'
          }
        }
      ]
    },
    {
      title: '租赁信息',
      type: 'wrapper',
      children: [
        {
          title: '租赁套餐',
          type: 'rent',
          formProp: {
            label: '租赁套餐',
            name: 'rent_plan'
            // rules: [{ required: true, message: '请设置租赁套餐！' }]
          }
        },
        {
          title: '起租日',
          type: 'inputNumber',
          visibelCheck: true,
          checkName: 'checkRent',
          formProp: {
            label: '起租日',
            name: 'lease_start_date_set',
            rules: [{ required: true, message: '请输入起租日！' }],
            help: '起租日为租赁合同起租时间，默认起租日为确认收货日当天或发货后3天自动确认收货'
          },
          itemProp: {
            style: { width: '346px' },
            addonAfter: '天'
          }
        }
      ]
    },
    {
      title: '电商信息',
      type: 'wrapper',
      children: [
        {
          title: '买卖套餐',
          type: 'sell',
          formProp: {
            label: '买卖套餐',
            name: 'sell_plan'
            // rules: [{ required: true, message: '请设置买卖套餐！' }]
          }
        },
        {
          title: '最长确认收货',
          type: 'inputNumber',
          visibelCheck: true,
          checkName: 'checkSell',
          formProp: {
            label: '最长确认收货',
            name: 'buy_recvconfirm_days',
            rules: [{ required: true, message: '请输入最长确认收货！' }],
            help: '设置该日期为账单起算时间，默认起租日为确认收货日当天或发货后3天自动确认收货'
          },
          itemProp: {
            style: { width: '346px' },
            addonAfter: '天'
          }
        }
      ]
    },
    {
      title: '规格管理',
      type: 'wrapper',
      component: (
        <>
          <SpuCard></SpuCard>
          <SkuCard form={form}></SkuCard>
        </>
      )
    },
    {
      title: '商品介绍',
      type: 'wrapper',
      children: [
        {
          title: '商品图片',
          type: 'upload',
          formProp: {
            label: '商品图片',
            name: 'goods_pic',
            rules: [{ required: true, message: '请上传商品图片！' }],
            getValueFromEvent: e => normFile(e),
            valuePropName: 'fileList',
            multiple: true,
            help: '正方形比例，建议不超过2M，第一张为商品封面图，最多上传十张，可以拖拽调整图片顺序'
          },
          itemProp: {
            key: 'goods_pic',
            formProps: {
              name: 'file',
              listType: 'picture-card'
            },
            showIcon: true,
            maxCount: 5
          }
        },
        {
          title: '商品详情页',
          type: 'richText',
          formProp: {
            label: '商品详情页',
            name: 'goods_detail',
            rules: [{ required: true, message: '请输入起租日！' }],
            help: '产品详情页介绍页面，添加商品详情有利于提高商品转化率'
          },
          itemProp: {}
        }
      ]
    },
    {
      title: '物流配置',
      type: 'wrapper',
      children: [
        {
          title: '配送方式',
          type: 'checkbox',
          formProp: {
            label: '配送方式',
            name: 'delivery_types',
            rules: [{ required: true, message: '请设置配送方式' }],
            help: '设置运费到付后，需要商家在收到商品后自行支付运费，运费最终以物流公司计算为准。'
          },
          itemProp: {
            list: [
              {
                label: '快递发货',
                value: 'express_delivery'
              },
              {
                label: '上门自提',
                value: 'own_take'
              }
            ]
          }
        },
        {
          title: '快递运费',
          type: 'radio',
          options: 'vertical',
          formProp: {
            label: '快递运费',
            name: 'shipping_method',
            rules: [{ required: true, message: '' }],
            help: '设置运费到付后，需要租户在收到商品后自行支付运费，运费最终以物流公司计算为准。'
          },
          itemProp: {
            prop: {},
            list: [
              {
                label: '包邮',
                value: 1
              },
              {
                label: '运费到付（租户自付邮费）',
                value: 2
              }
            ]
          }
        },
        {
          title: '自提地址',
          type: 'selfPickup',
          options: 'vertical',
          visibelCheck: true,
          checkName: 'selfPickup',
          formProp: {
            label: '自提地址',
            rules: [{ required: true, message: '' }],
            help: '自提地址需要新增或编辑请至【店铺管理】-【配送管理】-【上门自提】中操作'
          },
          itemProp: {
            list: selfPickupList,
            reloadData: () => getSelfPickupList()
          }
        },
        {
          title: '归还快递',
          type: 'radio',
          options: 'vertical',
          formProp: {
            label: '归还快递',
            name: 'return_method',
            rules: [{ required: true, message: '' }],
            help: '设置运费到付后，需要商户在收到商品后自行支付运费，运费最终以物流公司计算为准。'
          },
          itemProp: {
            prop: {},
            list: [
              {
                label: '自付（租户自付邮费）',
                value: 1
              },
              {
                label: '到付（商家承担邮费）',
                value: 2
              }
            ]
          }
        },
        {
          title: '归还地址',
          type: 'select',
          formProp: {
            label: '归还地址',
            name: 'return_address_id',
            rules: [{ required: true, message: '请选择归还地址！' }],
            help: disabled ? (
              ''
            ) : (
              <Button type='link' onClick={e => triggerAddresModal(e)}>
                新增地址
              </Button>
            )
          },
          itemProp: {
            prop: {
              options: addressList
            }
          }
        }
      ]
    }
  ]

  useEffect(() => {
    SetDisable(disabled)

    init()

    return () => {
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
    }
  }, [])

  const goEdit = () => {
    history.replace(`/product?type=2&id=${id}`)
  }

  const handleTempStorage = () => {
    timer = setTimeout(() => {
      const data = form.getFieldsValue()
      localStorage.setItem('tempStorage', JSON.stringify(data))
      handleTempStorage()
    }, 5000)
  }

  const normFile = e => {
    return e.map(i => i.value)
  }

  const handleChangeGainTab = e => {
    setGainTab(e)
  }

  useEffect(() => {
    setNeedFineness(goodsType === 2)
  }, [goodsType])

  useEffect(() => {
    const newList = [...defaultFormList]
    if (gainSet && gainSet.length) {
      newList.push({
        title: '其他信息',
        type: 'tabWrapper',
        wrapperProps: {
          tabList: [
            { key: 'rent', tab: '租赁套餐' },
            { key: 'buy', tab: '买卖套餐' }
          ],
          activeTabKey: gainTab,
          onTabChange: handleChangeGainTab
        },
        component: (
          <Form.Item name='gain_info' label='增值服务' help='增值服务需要新增请至【商品中心】-【增值服务管理】中操作'>
            <GaintSet disabled={disabled} data={gainSet} form={form} gainTab={gainTab} />
          </Form.Item>
        )
      })
    }
    setFormList(newList)
  }, [goodsFineness, gainSet, addressList, goodsClassList, gainTab, selfPickupList])

  useEffect(() => {
    if (originPackagePlan && originPackagePlan.length && goodsInfo) {
      const { spu, sku, rent_plan } = goodsInfo
      const initial = {
        ...goodsInfo
      }
      if (spu) {
        spu.forEach(i => {
          initial[`spu_name_${i.id}`] = i.name
          initial[`spu_value_${i.id}`] = i.values
          if (i.values) {
            i.values.forEach(it => {
              it.id = it.id || getUnique(6)
              initial[`spu_sku_name_${it.id}`] = it.sku_value
              if (it.value_attribute) {
                initial[`spu_sku_pic_${it.id}`] = it.value_attribute
              }
            })
          }
        })
      }
      if (rent_plan) {
        const formatedRent = rent_plan.map(i => ({
          ...i,
          id: i.rent_plan_id,
          type: i.use_scope,
          checked: true,
          rent_period: i.rent_period_ids.map(it =>
            originPackagePlan
              .find(item => item.id === i.rent_plan_id)
              .rent_period.find(period => period.id === Number(it))
          )
        }))
        initial.rent_plan = formatedRent.filter(i => !i.use_scope || i.use_scope === 'rent')
        initial.sell_plan = formatedRent.filter(i => i.use_scope === 'buy')
        formatedRent.forEach(i => {
          initial.rent_plan = formatedRent.filter(i => !i.use_scope || i.use_scope === 'rent')
          if (!i.use_scope || i.use_scope === 'rent') {
            initial[`support_buyout_${i.id}`] = i.support_buyout
            initial[`package_name_${i.id}`] = i.package_name
            initial[`period_${i.id}`] = i.rent_period_ids.map(it => Number(it))
          } else if (i.use_scope === 'buy') {
            initial[`support_fixed_price_${i.id}`] = i.support_fixed_price
            initial[`sell_package_name__${i.id}`] = i.package_name
            initial[`first_price-${i.id}`] = i.first_pay_ratio
            initial[`sell_period_${i.id}`] = i.rent_period_ids.map(i => Number(i))
            initial[`periods_amount-${i.id}`] = i.terms
          }
        })
      }

      if (sku) {
        sku.forEach(i => {
          const currentPlan = rent_plan.find(plan => plan.id === i.grp_id)
          if (currentPlan.rent_period_ids) {
            currentPlan.rent_period_ids.forEach(periodId => {
              const key = `period_id_${periodId}`
              const totalDays = originPackagePlan
                .find(r => r.id === currentPlan.rent_plan_id)
                .rent_period.find(rp => rp.id === Number(periodId)).total_days
              const value = i[key]
              initial[`${i.id}-${key}`] = value
              i[`${key}-perday`] = (value / totalDays).toFixed(2) + '元/天'
            })
          }
          initial[`${i.id}-buyout_price`] = i.buyout_price
          initial[`${i.id}-deposit`] = i.deposit
          initial[`${i.id}-selling_price`] = i.selling_price
          initial[`${i.id}-store`] = i.store
        })
      }
      setInitialValues(initial)
      setTimeout(() => {
        form.resetFields()
      }, 100)
    }
  }, [originPackagePlan, goodsInfo])

  const init = () => {
    if (pageType === 1) {
      // 新增
      const data = localStorage.getItem('tempStorage')

      if (data && data !== '{}') {
        const temp = JSON.parse(data)
        setInitialValues(temp)
        form.resetFields()
        setTimeout(() => {
          form.resetFields()
        }, 100)
      }

      handleTempStorage()
    } else {
      // 编辑
      if (id) {
        getGoodsInfo()
      } else {
        message.error('商品ID有误')
      }
    }

    getGoodFineness()
    getRentPlan()
    getGainSet()
    getReturnAddress()
    getGoodsClass()
    getTerms()
    getSelfPickupList()
  }

  const getSelfPickupList = async () => {
    setPickupListLoading(true)
    const res = await GetActiveOwnTakeList()
    setPickupListLoading(false)
    setSelfPickupList(res)
  }

  const getTerms = async () => {
    const res = await GetTerms()
    setSellTermList(res)
  }

  const getGoodsInfo = async () => {
    const res = await GetGoodsDetail({ id })
    if (res) setGoodsInfo(res)
  }

  const getGoodsClass = async () => {
    const res = await GetGoodsClass()
    setGoodsClassList(res)
  }

  const getReturnAddress = async () => {
    let params = null
    if (merchant_id) {
      params = { merchant_id }
    }
    const res = await GetAddressList(params)
    setAddressList(
      res
        ? res.map(i => ({
            label: `${i.consignee_province}${i.consignee_city}${i.consignee_area}${i.cons_detail_address}`,
            value: i.id,
            key: i.id
          }))
        : []
    )
  }

  const getGainSet = async () => {
    const res = await GetGainSet()
    setGainSet(res)
  }

  const getRentPlan = async () => {
    const res = await GetRentPlan()
    setOriginPackagePlan(res)
    setRentPlan(res.filter(i => i.type === 'rent') || [])
    setSellPlan(res.filter(i => i.type === 'buy') || [])
  }

  const getGoodFineness = async () => {
    const res = await GetGoodFineness()
    setGoodsFineness(
      res.map(i => ({
        label: i.name,
        value: i.id
      })) || []
    )
  }

  const onSubmit = type => {
    saveType.current = type
    form
      .validateFields()
      .then()
      .catch(err => {
        if (err.errorFields.length) {
          message.warning('请完善表单必要信息')
        }
      })
    form.submit()
  }

  const onReset = () => {
    setInitialValues(originInitial)
    localStorage.removeItem('tempStorage')
    form.resetFields()
    setTimeout(() => {
      form.resetFields()
    }, 100)
  }

  // 关闭当前页面
  const handleClosePage = () => {
    window.close()
  }

  // 操作商品 复制 / 新建
  const handleProductResult = type => {
    history.replace('/product?type=1')
    Modal.destroyAll()
    if (type === 'new') {
      onReset()
    }
  }

  const onFinish = async e => {
    const { rent_plan = [], sell_plan = [] } = e
    const planList = rent_plan.concat(sell_plan).filter(i => i.checked)

    if (!planList.length) {
      message.warning('需要设置至少一种租赁套餐或者买卖套餐')
      return false
    }
    setPageLoading(true)
    if (e.delivery_types.includes('own_take')) {
      const checkData = await GetOwnTakeCount()
      if (!checkData) {
        setPageLoading(false)
        getSelfPickupList()
        message.warning('设置上门自提必须存在启用中的自提点')
        return
      }
    }
    const params = {
      ...e,
      rent_plan: planList
        .filter(i => i.checked)
        .map(i => ({
          ...i,
          rent_plan_id: i.id,
          rent_period_ids: i.rent_period.map(rp => rp.id),
          use_scope: i.type
        }))
    }
    if (pageType === 2 && id) {
      params.id = id
    }

    if (saveType.current) {
      const saveMethod = [SaveGood, SaveAndActiveGoods][saveType.current - 1]
      const res = await saveMethod(params)
      setPageLoading(false)
      if (res) {
        // message.success('操作成功')
        // if (pageType === 1) {
        //   localStorage.removeItem('tempStorage')
        //   history.replace(`/product?type=2&id=${res}`)
        // }
        modal.confirm({
          width: 600,
          title: '商品操作结果',
          icon: null,
          content: (
            <Result
              status='success'
              title='保存成功'
              subTitle='商品已保存成功，您可以继续操作或者关闭页面'
              extra={[
                <Button key='closePage' type='primary' danger onClick={handleClosePage}>
                  关闭页面
                </Button>,
                <Button key='copyProduct' onClick={() => handleProductResult('copy')}>
                  复制一份
                </Button>,
                <Button key='newProduct' type='primary' onClick={() => handleProductResult('new')}>
                  新建一份
                </Button>
              ]}
            />
          ),
          footer: null
        })
      }
      saveType.current = 0
    }
  }

  const checkVisibel = (data, dom) => {
    const { visibelCheck, checkName } = data

    if (visibelCheck && checkName) {
      switch (checkName) {
        case 'fineness':
          return needFineness ? dom : null
        case 'checkRent':
          let rentFlag = Boolean(Rent.filter(i => i.checked).length)
          return rentFlag ? dom : null
        case 'checkSell':
          let sellFlag = Boolean(Sell.filter(i => i.checked).length)
          return sellFlag ? dom : null
        case 'selfPickup':
          let selfPickupFlag = form.getFieldValue('delivery_types')
            ? form.getFieldValue('delivery_types').includes('own_take')
            : false
          return selfPickupFlag ? dom : null
      }
    } else {
      return dom
    }
  }

  const reRenderForm = () => {
    setFormList([...FormList])
  }

  const renderFormList = list => {
    return list.map(formItem => {
      const { type, title, wrapperProps, children, formProp, itemProp, component, options } = formItem

      switch (type) {
        case 'wrapper':
          return (
            <Card title={title} key={title} style={{ marginBottom: '16px' }}>
              {component ? component : renderFormList(children)}
            </Card>
          )
        case 'tabWrapper':
          return (
            <Card title={title} key={title} style={{ marginBottom: '16px' }} {...wrapperProps}>
              {component ? component : renderFormList(children)}
            </Card>
          )
        case 'input':
          return (
            <Form.Item {...formProp} key={title}>
              <Input disabled={disabled} {...itemProp} />
            </Form.Item>
          )
        case 'inputNumber':
          return checkVisibel(
            formItem,
            <Form.Item {...formProp} key={title}>
              <InputNumber disabled={disabled} {...itemProp} />
            </Form.Item>
          )
        case 'radio':
          return checkVisibel(
            formItem,
            <Form.Item {...formProp} key={title}>
              <Radio.Group disabled={disabled} {...itemProp.prop}>
                {options === 'vertical' ? (
                  <Space direction='vertical' style={{ paddingTop: '5px' }}>
                    {itemProp.list && itemProp.list.length
                      ? itemProp.list.map(radio => (
                          <Radio value={radio.value} key={radio.value}>
                            {radio.label}
                          </Radio>
                        ))
                      : null}
                  </Space>
                ) : itemProp.list && itemProp.list.length ? (
                  itemProp.list.map(radio => (
                    <Radio value={radio.value} key={radio.value}>
                      {radio.label}
                    </Radio>
                  ))
                ) : null}
              </Radio.Group>
            </Form.Item>
          )
        case 'tag':
          return checkVisibel(
            formItem,
            <Form.Item {...formProp} key={title}>
              <TagInput disabled={disabled}></TagInput>
            </Form.Item>
          )
        case 'select':
          return checkVisibel(
            formItem,
            <Form.Item {...formProp} key={title}>
              <Select disabled={disabled} {...itemProp.prop} />
            </Form.Item>
          )
        case 'rent':
          return (
            <Form.Item {...formProp} key={title}>
              <RentPlanCard disabled={disabled} rentPlan={rentPlan} formRef={form} />
            </Form.Item>
          )
        case 'sell':
          return (
            <Form.Item {...formProp} key={title}>
              <SellPlanCard disabled={disabled} sellPlan={sellPlan} formRef={form} sellTermList={sellTermList} />
            </Form.Item>
          )
        case 'upload':
          return (
            <Form.Item {...formProp} key={title}>
              <Upload disabled={disabled} {...itemProp} className={styles.goods_desc_upload} />
            </Form.Item>
          )
        case 'richText':
          return (
            <Form.Item {...formProp} key={title}>
              <RichText disabled={disabled} {...itemProp} />
            </Form.Item>
          )
        case 'cascader':
          return (
            <Form.Item {...formProp} key={title}>
              <Cascader disabled={disabled} {...itemProp} />
            </Form.Item>
          )
        case 'checkbox':
          return (
            <Form.Item {...formProp} key={title}>
              <Checkbox.Group disabled={disabled} onChange={reRenderForm} style={{ width: '100%' }}>
                {itemProp.list.map(i => (
                  <Checkbox key={i.label} value={i.value}>
                    {i.label}
                  </Checkbox>
                ))}
              </Checkbox.Group>
            </Form.Item>
          )
        case 'selfPickup':
          return checkVisibel(
            formItem,
            <Form.Item {...formProp} key={title}>
              <SelfPickup {...itemProp} loading={pickupListLoading} />
            </Form.Item>
          )
      }
    })
  }

  const handleAddAddress = async ({ area, ...props }) => {
    const params = {
      ...props,
      consignee_province: area[0],
      consignee_city: area[1],
      consignee_area: area[2]
    }
    setAddressModalLoading(true)
    const res = await SaveReturnAddress(params)
    if (res) {
      getReturnAddress()
      setAddressModalLoading(false)
      triggerAddresModal()
    }
  }

  const triggerAddresModal = () => {
    addressForm.resetFields()
    setAddressModalFlag(!addressModalFlag)
  }

  const handleOk = () => {
    addressForm.submit()
  }

  const formatExtra = () => {
    return pageType === 3
      ? platformType
        ? [
            <Button key='goedit' htmlType='reset' onClick={goEdit}>
              编辑
            </Button>
          ]
        : []
      : pageType === 2
      ? goodsInfo && goodsInfo.after_approval_status === 1
        ? [
            <Button key='reset' htmlType='reset' onClick={onReset}>
              重置
            </Button>,
            <Button key='submit' type='primary' onClick={() => onSubmit(1)}>
              保存
            </Button>
          ]
        : [
            <Button key='reset' htmlType='reset' onClick={onReset}>
              重置
            </Button>,
            <Button key='submit' type='primary' onClick={() => onSubmit(1)}>
              保存
            </Button>,
            <Button key='saveAndPublic' type='primary' onClick={() => onSubmit(2)}>
              保存并上架
            </Button>
          ]
      : [
          <Button key='reset' htmlType='reset' onClick={onReset}>
            重置
          </Button>,
          <Button key='submit' type='primary' onClick={() => onSubmit(1)}>
            保存
          </Button>,
          <Button key='saveAndPublic' type='primary' onClick={() => onSubmit(2)}>
            保存并上架
          </Button>
        ]
  }

  useEffect(() => {
    document.getElementsByClassName('ant-page-header')[0].style.width = `${contentWidth}px`
  }, [contentWidth])

  return (
    <div className={styles.page_wrapper}>
      <Spin spinning={pageLoading}>
        <PageContainer
          header={{
            fixedHeader: true,
            title: (
              <div className={styles.header_title}>
                <span>{pageType === 2 ? '编辑商品' : pageType === 3 ? '查看产品' : '新增商品'}</span>
                <Divider type='vertical' />
                <span className={styles.header_desc}>商品发布管理页</span>
              </div>
            ),
            extra: formatExtra()
          }}
        >
          <Form form={form} name='goods_form' {...formItemLayout} onFinish={onFinish} initialValues={initialValues}>
            {renderFormList(FormList)}
          </Form>
        </PageContainer>
      </Spin>
      <Modal
        title='新增地址'
        open={addressModalFlag}
        onOk={handleOk}
        confirmLoading={addressModalLoading}
        onCancel={triggerAddresModal}
        maskClosable={false}
        destroyOnClose
      >
        <Form form={addressForm} name='addressForm' {...addressLayout} onFinish={handleAddAddress}>
          <Form.Item name='area' label='所在地区' rules={[{ required: true, message: '请设置地区！' }]}>
            <Cascader options={CITY} placeholder='请选择' />
          </Form.Item>
          <Form.Item
            name='cons_detail_address'
            label='详细地址'
            rules={[{ required: true, message: '请输入详细地址' }]}
          >
            <Input.TextArea placeholder='请输入' />
          </Form.Item>
          <Form.Item
            name='consignee_name'
            label='收货人姓名'
            rules={[{ required: true, message: '请输入收货人姓名！' }]}
          >
            <Input placeholder='请输入' />
          </Form.Item>
          <Form.Item name='consignee_tel' label='手机号码' rules={[{ required: true, message: '请输入手机号码！' }]}>
            <Input placeholder='请输入' />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
